from django.shortcuts import render
from rest_framework.generics import CreateAPIView, RetrieveAPIView, DestroyAPIView
from rest_framework.views import APIView
from .serializers import MyTokenSerializer, CreateUserSerializer, UserDetailSerializer, UserAddressSerializer, \
    MyrefreshTokenSerializer, RefreshTokenSerializer, RoleSerializer, UserSerializer, adminUserDetailSerializer
from rest_framework.response import Response
from rest_framework import status
from .models import Role, User
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework_simplejwt.views import TokenViewBase, TokenObtainPairView
from rest_framework.decorators import action, api_view
from django.contrib.auth import authenticate

# Create your views here.
class UserView(CreateAPIView):
    """用户注册"""
    serializer_class = CreateUserSerializer  # 指定序列化器


class CreateUserAPIView(APIView):
    """管理员新增用户"""

    def post(self, request):
        # 从请求中获取表单数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')

        # 检查表单数据是否完整
        if not (username and password and mobile):
            return Response({'error': 'Missing required fields'}, status=status.HTTP_400_BAD_REQUEST)

        # 创建新用户
        user = User.objects.create_user(username=username, password=password)
        user.mobile = mobile
        user.save()

        # 返回成功响应
        return Response({'success': True})


class RoleViewSet(ModelViewSet):
    queryset = Role.objects.all()
    serializer_class = RoleSerializer


class UserRolesView(APIView):
    """用于修改用户权限"""

    def post(self, request, pk):
        try:
            user = User.objects.get(pk=pk)
        except User.DoesNotExist:
            return Response({'status': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)

        role_names = request.data.get('roles', [])
        user.roles.clear()

        for role_name in role_names:
            role, created = Role.objects.get_or_create(name=role_name)
            user.roles.add(role)

        return Response({'status': '用户角色更新成功！'})


class UserViewSet(ModelViewSet):
    """主要用来获取用户的一些信息，当时由于增加了role导致视图有点混乱"""
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @action(detail=True, methods=['get'])
    def user(self, request, pk=None):
        user = self.get_object()
        roles = user.roles.all()
        serializer = RoleSerializer(roles, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def set_roles(self, request, pk=None):
        user = self.get_object()
        role_names = request.data.get('roles')
        user.roles.clear()
        for role_name in role_names:
            role, created = Role.objects.get_or_create(name=role_name)
            user.roles.add(role)
        return Response({'status': '用户角色更新成功！'})

    @action(detail=True, methods=['post'])
    def add_role(self, request, pk=None):
        user = self.get_object()
        role_name = request.data.get('name')
        role, created = Role.objects.get_or_create(name=role_name)
        user.roles.add(role)
        return Response({'status': '角色添加成功！'})

    @action(detail=True, methods=['post'])
    def remove_role(self, request, pk=None):
        user = self.get_object()
        role_name = request.data.get('name')
        role = Role.objects.get(name=role_name)
        user.roles.remove(role)
        return Response({'status': '角色删除成功！'})

    @action(detail=True, methods=['delete'])
    def remove_user(self, request, pk=None):
        user = self.get_object()
        user.delete()
        return Response({'status': '该用户删除成功！'})


class ChangePassword(APIView):
    def put(self, request):
        # 获取请求中的用户名和新密码
        username = request.data.get('username')
        new_password = request.data.get('new_password')

        # 获取要修改密码的用户对象
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return Response({'error': '用户不存在'}, status=status.HTTP_400_BAD_REQUEST)

        # 修改密码
        user.set_password(new_password)
        user.save()

        return Response({'success': '密码修改成功'}, status=status.HTTP_200_OK)


class Updateuserstatus(APIView):
    """更改用户状态"""

    def put(self, request, username):
        """修改用户状态"""
        user = User.objects.filter(username=username)[0]
        if user.is_active:
            user.is_active = False
        else:
            user.is_active = True
        user.save()
        return Response({"success": True})


# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """根据用户名来获取用户手机号码，该用户下单数"""

    def get(self, request, username):
        """获取指定用户名数量"""
        user = User.objects.filter(username=username)
        serializer = UserDetailSerializer(user, many=True)
        orders_count = Order.object.filter(username=username).count()

        print(orders_count)
        return Response(serializer.data[0])


class MobileCountView(APIView):
    """手机号码数量"""

    def get(self, request, mobile):
        """获取指定用户名数量"""
        count = User.objects.filter(mobile=mobile).count()
        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)


class UsersCountView(APIView):
    """用户数量"""

    def get(self, request):
        """获取用户总数量"""
        user_count = User.objects.all().count()
        users = User.objects.all()
        # print(users);
        common_count = 0
        admin_count = 0
        for user in users:
            common_roles = user.roles.filter(name="common")
            admin_roles = user.roles.filter(name="admin")
            if common_roles.count() != 0:
                common_count += 1
            if admin_roles.count() != 0:
                admin_count += 1
        data = {
            'user_count': user_count,
            'common_count': common_count,
            'admin_count': admin_count
        }
        return Response(data)


class AdminUserDetailView(APIView):
    """管理员用户信息详情展示"""

    def get(self, request):
        """获取管理员用户信息详情"""
        users = User.objects.all()
        # print(users);
        adminUsers = []
        for user in users:
            admin_roles = user.roles.filter(name="admin")
            if admin_roles.count() != 0:
                adminUsers.append(user)
        print(adminUsers)
        serializer = UserSerializer(adminUsers, many=True)
        return Response(serializer.data)


class Login2View(TokenObtainPairView):
    # 引用上面自定义的序列化类
    serializer_class = MyTokenSerializer


class refreshTokenView(TokenObtainPairView):
    # 引用上面自定义的序列化类
    serializer_class = MyrefreshTokenSerializer


class RefreshTokensView(APIView):
    # permission_classes = [IsAuthenticated]

    def post(self, request, format=None):
        serializer = RefreshTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        refresh = serializer.validated_data['refreshToken']
        access = refresh.access_token
        expires = access['exp']
        response_data = {
            'accessToken': str(access),
            'refreshToken': str(refresh),
            'expires': expires,
        }
        return Response({'success': True, 'data': response_data})


class Test(APIView):
    # permission_classes = []
    def get(self, request):
        print(request.auth.payload)
        return Response('aa')


class AddressViewSet(GenericViewSet):
    """用户地址的增删改查"""
    serializer_class = UserAddressSerializer

    # queryset =
    def create(self, request):
        user = request.user
        count = user.address.all().count
        # 新增地址数量有上限
        if count >= 20:
            return Response({'message': '收获地址存在上限'}, status=status.HTTP_400_BAD_REQUEST)
        serializer = self.get_serializer(request.data)
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
